<template>
  <div class="user-management">
    <a-card>
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="queryParams" class="search-form">
        <a-form-item :label="t('user.username')">
          <a-input v-model:value="queryParams.username" :placeholder="t('user.username')" allow-clear />
        </a-form-item>
        <a-form-item :label="t('user.realName')">
          <a-input v-model:value="queryParams.realName" :placeholder="t('user.realName')" allow-clear />
        </a-form-item>
        <a-form-item :label="t('user.phone')">
          <a-input v-model:value="queryParams.phone" :placeholder="t('user.phone')" allow-clear />
        </a-form-item>
        <a-form-item :label="t('user.status')">
          <a-select v-model:value="queryParams.status" :placeholder="t('user.status')" allow-clear>
            <a-select-option :value="1">{{ t('common.normal') }}</a-select-option>
            <a-select-option :value="0">{{ t('common.disabled') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              {{ t('common.search') }}
            </a-button>
            <a-button @click="handleReset">
              <template #icon><redo-outlined /></template>
              {{ t('common.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            {{ t('common.add') }}
          </a-button>
        </a-space>
      </div>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? t('common.normal') : t('common.disabled') }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                {{ t('common.edit') }}
              </a-button>
              <a-button type="link" size="small" @click="handleResetPassword(record)">
                {{ t('user.resetPassword') }}
              </a-button>
              <a-popconfirm
                :title="t('user.confirmDelete')"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>
                  {{ t('common.delete') }}
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :width="600"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item :label="t('user.username')" name="username">
          <a-input 
            v-model:value="formData.username" 
            :placeholder="t('user.username')" 
            :disabled="formType === 'edit'" 
          />
        </a-form-item>
        <a-form-item :label="t('user.realName')" name="realName">
          <a-input v-model:value="formData.realName" :placeholder="t('user.realName')" />
        </a-form-item>
        <a-form-item :label="t('user.phone')" name="phone">
          <a-input v-model:value="formData.phone" :placeholder="t('user.phone')" />
        </a-form-item>
        <a-form-item :label="t('user.email')" name="email">
          <a-input v-model:value="formData.email" :placeholder="t('user.email')" />
        </a-form-item>
        <a-form-item :label="t('user.status')" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="1">{{ t('common.normal') }}</a-radio>
            <a-radio :value="0">{{ t('common.disabled') }}</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 重置密码弹窗 -->
    <a-modal
      v-model:visible="resetPasswordVisible"
      :title="t('user.resetPassword')"
      @ok="handleResetPasswordOk"
      @cancel="handleResetPasswordCancel"
      :width="400"
    >
      <a-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item :label="t('user.newPassword')" name="password">
          <a-input-password v-model:value="resetPasswordForm.password" :placeholder="t('user.newPassword')" />
        </a-form-item>
        <a-form-item :label="t('user.confirmPassword')" name="confirmPassword">
          <a-input-password v-model:value="resetPasswordForm.confirmPassword" :placeholder="t('user.confirmPassword')" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {
  createUser,
  deleteUser,
  getUserList,
  resetPassword,
  updateUser
} from '@/api/user'
import type { UserInfo, UserQuery } from '@/types/user.type'
import {
  PlusOutlined,
  RedoOutlined,
  SearchOutlined
} from '@ant-design/icons-vue'
import type { FormInstance, TablePaginationConfig } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

// 查询参数
const queryParams = reactive<UserQuery>({
  current: 1,
  size: 10,
  username: '',
  realName: '',
  phone: '',
  status: undefined
})

// 表格列定义
const columns = [
  {
    title: t('user.username'),
    dataIndex: 'username',
    key: 'username',
    width: 120
  },
  {
    title: t('user.realName'),
    dataIndex: 'realName',
    key: 'realName',
    width: 120
  },
  {
    title: t('user.phone'),
    dataIndex: 'phone',
    key: 'phone',
    width: 120
  },
  {
    title: t('user.email'),
    dataIndex: 'email',
    key: 'email',
    width: 180
  },
  {
    title: t('user.status'),
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: t('user.createTime'),
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: t('common.action'),
    key: 'action',
    fixed: 'right',
    width: 250
  }
]

// 表格数据
const tableData = ref<UserInfo[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive<TablePaginationConfig>({
  total: 0,
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true
})

// 表单相关
const formRef = ref<FormInstance>()
const modalVisible = ref(false)
const modalTitle = ref('')
const formType = ref<'add' | 'edit'>('add')
const formData = reactive<Partial<UserInfo>>({
  username: '',
  realName: '',
  phone: '',
  email: '',
  status: 1
})

// 表单校验规则
const rules = {
  username: [{ required: true, message: t('user.usernameRequired') }],
  realName: [{ required: true, message: t('user.realNameRequired') }],
  phone: [{ required: true, message: t('user.phoneRequired') }],
  email: [{ required: true, message: t('user.emailRequired'), type: 'email' }],
  status: [{ required: true, message: t('user.statusRequired') }]
}

// 重置密码相关
const resetPasswordVisible = ref(false)
const resetPasswordFormRef = ref<FormInstance>()
const resetPasswordForm = reactive({
  id: '',
  password: '',
  confirmPassword: ''
})

// 重置密码校验规则
const resetPasswordRules = {
  password: [{ required: true, message: '请输入新密码' }],
  confirmPassword: [
    { required: true, message: '请再次输入新密码' },
    {
      validator: async (_rule: any, value: string) => {
        if (value !== resetPasswordForm.password) {
          throw new Error('两次输入的密码不一致')
        }
      }
    }
  ]
}

// 新增
const handleAdd = () => {
  formType.value = 'add'
  modalTitle.value = t('user.add')
  Object.assign(formData, {
    username: '',
    realName: '',
    phone: '',
    email: '',
    status: 1
  })
  modalVisible.value = true
}

// 编辑
const handleEdit = (record: UserInfo) => {
  formType.value = 'edit'
  modalTitle.value = t('user.edit')
  const { createTime, updateTime, roles, ...formDataToEdit } = record
  Object.assign(formData, formDataToEdit)
  modalVisible.value = true
}

// 删除
const handleDelete = async (record: UserInfo) => {
  try {
    await deleteUser([record.id])
    message.success(t('common.success'))
    fetchData()
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 重置密码
const handleResetPassword = (record: UserInfo) => {
  resetPasswordForm.id = record.id
  resetPasswordForm.password = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordVisible.value = true
}

// 重置密码确认
const handleResetPasswordOk = async () => {
  try {
    await resetPasswordFormRef.value?.validate()
    await resetPassword({
      userId: Number(resetPasswordForm.id),
      password: resetPasswordForm.password
    })
    message.success(t('common.success'))
    resetPasswordVisible.value = false
  } catch (error: any) {
    if (error.errorFields) {
      return
    }
    message.error(error.message || t('common.failed'))
  }
}

// 重置密码取消
const handleResetPasswordCancel = () => {
  resetPasswordVisible.value = false
  resetPasswordFormRef.value?.resetFields()
}

// 弹窗确认
const handleModalOk = async () => {
  try {
    await formRef.value?.validate()
    const { createTime, updateTime, roles, ...formDataToSubmit } = formData
    if (formData.id) {
      await updateUser(formDataToSubmit as UserInfo)
      message.success('更新成功')
    } else {
      await createUser(formDataToSubmit as Omit<UserInfo, 'id'>)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchData()
  } catch (error: any) {
    if (error.errorFields) {
      return
    }
    message.error(error.message || '操作失败')
  }
}

// 弹窗取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getUserList(queryParams)
    if (res && res.records) {
      tableData.value = res.records
      pagination.total = res.total || 0
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (error: any) {
    message.error(error.message || '获取用户列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="less" scoped>
.user-management {
  .search-form {
    margin-bottom: 16px;
  }

  .table-operations {
    margin-bottom: 16px;
  }
}
</style> 